package cn.csust.net2.manager.client.module;

import java.util.Date;
import java.util.List;

import cn.csust.net2.manager.client.panel.SecurityWindow;
import cn.csust.net2.manager.client.resources.Resources;
import cn.csust.net2.manager.client.ux.BeanRowEditor;
import cn.csust.net2.manager.client.ux.ExpandGrid;
import cn.csust.net2.manager.client.ux.ServiceCallback;
import cn.csust.net2.manager.shared.po.PO;
import cn.csust.net2.manager.shared.po.Student;
import cn.csust.net2.manager.shared.po.Teacher;
import cn.csust.net2.manager.shared.po.User;
import cn.csust.net2.manager.shared.service.AuthorizationService;
import cn.csust.net2.manager.shared.service.AuthorizationServiceAsync;
import cn.csust.net2.manager.shared.util.ClassForNameAble;
import cn.csust.net2.manager.shared.vo.Config;
import cn.csust.net2.manager.shared.vo.GridConfig;

import com.extjs.gxt.ui.client.Style.ButtonScale;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.IconAlign;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.BeanModelFactory;
import com.extjs.gxt.ui.client.data.BeanModelLookup;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.Record.RecordUpdate;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.store.StoreEvent;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.button.ButtonGroup;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.CardLayout;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.AbstractImagePrototype;

/**
 * @author 韩忠金
 * @version 创建时间：2012-1-30 上午10:46:19 类说明
 */
@ClassForNameAble
public class Authorization extends BaseModule {
	private LayoutContainer layout;

	public Authorization() {
		this.setText("权限管理");
		this.setId("权限管理");
		this.setClosable(true);
		this.setLayout(new FitLayout());
		layout = new LayoutContainer();
		layout.setLayoutOnChange(true);
		layout.setLayout(new BorderLayout());
		init();
//	List<PropertyAssist> s = new User().getAssist().getPropertyAssists();
//	for(PropertyAssist ss:s){
//		System.out.println(ss.getDisplayName()+""+ss.getEditorType());
//	}
	}

	public void init() {

		// initUpUI();
		initDownUI();
		initLayoutInfo();
	}

	/**
	 * 初始化整体布局信息
	 */
	public void initLayoutInfo() {
		// Border布局

		// 讲上下部分合并进布局中
		// layout.add(up,new BorderLayoutData(LayoutRegion.NORTH));
		this.add(layout);
		this.addStyleName("pad-text");
	}

	private ExpandGrid<User> grid;
	private ContentPanel cp;
	private AuthorizationServiceAsync myService;
	/**
	 * 初始化下部分的界面
	 */
	public void initDownUI() {
		// 用户列表表格
		myService = GWT.create(AuthorizationService.class);
		
		grid = new ExpandGrid<User>(new User(), myService);
		grid.getStore().addListener(Store.Add, new StoreListener());
		grid.getStore().addListener(Store.Update, new StoreListener());
		grid.getStore().addListener(Store.Remove, new StoreListener());
		grid.setColumnLines(true);
		rowEditor = new BeanRowEditor<User>();
		grid.addPlugin(rowEditor);
		cp = new ContentPanel();
		initTool();
		cp.setWidth("100%");
		cp.setHeight("80%");
		cp.setHeaderVisible(false);
		cp.setLayout(new FitLayout());
		cp.add(grid);
		cp.setBottomComponent(grid.getToolBar());
		layout.add(cp, new BorderLayoutData(LayoutRegion.CENTER));
	}

	private void initTool() {
		/**
		 * 创建工具栏
		 */

		ToolBar tb = new ToolBar();
		// 增加和删除按钮，修改
		Button securityManager = new Button("权限管理");
		securityManager.setIconAlign(IconAlign.TOP);
		securityManager.setScale(ButtonScale.LARGE);
		securityManager.setIcon(AbstractImagePrototype.create(Resources.ICONS.details()));
		securityManager.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
//				MessageBox.alert("提示", "点击权限管理按钮", null);
				securityManager();
			}
		});
		// 增加和删除按钮，修改
		Button add = new Button("增加");
		add.setIconAlign(IconAlign.TOP);
		add.setScale(ButtonScale.LARGE);
		add.setIcon(AbstractImagePrototype.create(Resources.ICONS.toolBarAdd()));
		add.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				//MessageBox.alert("提示", "点击增加按钮", null);
				add();
			}
		});
		Button delete = new Button("删除");
		delete.setIconAlign(IconAlign.TOP);
		delete.setScale(ButtonScale.LARGE);
		// delete.setHeight("90%");
		delete.setIcon(AbstractImagePrototype.create(Resources.ICONS.toolBarDelete()));
		delete.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				//MessageBox.alert("提示", "点击删除按钮", null);
				delete();
			}
		});
		Button save = new Button("保存");
		save.setIconAlign(IconAlign.TOP);
		save.setScale(ButtonScale.LARGE);
		// delete.setHeight("90%");
		save.setIcon(AbstractImagePrototype.create(Resources.ICONS.toolBarDelete()));
		save.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				MessageBox.alert("提示", "点击保持按钮", null);
				save();
			}
		});
		Button back = new Button("撤销");
		back.setIconAlign(IconAlign.TOP);
		back.setScale(ButtonScale.LARGE);
		// delete.setHeight("90%");
		back.setIcon(AbstractImagePrototype.create(Resources.ICONS.toolBarDelete()));
		back.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				MessageBox.alert("提示", "点击撤销按钮", null);
				//delete();
				back();
			}
		});
		Button update = new Button("修改");
		update.setIconAlign(IconAlign.TOP);
		update.setScale(ButtonScale.LARGE);
		update.setIcon(AbstractImagePrototype.create(Resources.ICONS.toolBarModify()));
		update.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
			//	MessageBox.alert("提示", "点击修改按钮", null);
				modify();
				
			}
		});
		
		// Card布局的条件面板
		ContentPanel condition = new ContentPanel();
		condition.setHeaderVisible(false);
		condition.setWidth(500);
		CardLayout cardLayout = new CardLayout();
		condition.setLayout(cardLayout);

		final SimpleComboBox<String> combo = new SimpleComboBox<String>();
		combo.setFieldLabel("用户类型");
		combo.setTriggerAction(TriggerAction.ALL);
		combo.add(ByGrade.ADDRESS);
		combo.add(ByGrade.BEAN_JI);
		combo.add(ByGrade.BIRTHDAY);
		combo.add(ByGrade.BIRTHPLACE);
		combo.add(ByGrade.CELLPHONE);
		combo.add(ByGrade.DORMITORY);
		combo.add(ByGrade.NAME);
		combo.add(ByGrade.NATION);
		combo.add(ByGrade.POST_CODE);
		combo.add(ByGrade.QQ);
		combo.add(ByGrade.SEX);
		combo.add(ByGrade.SPECIALTY);
		combo.add(ByGrade.STUDENT_NUMBER);
		combo.add(ByGrade.TELLPHONE);
		Label l1 = new Label("索引属性：");
		Label l2 = new Label("索引数值：");
		final TextField<String> lastName = new TextField<String>();
		Button search = new Button("模糊查询");
		search.setIconAlign(IconAlign.TOP);
		search.setScale(ButtonScale.LARGE);
		search.setIcon(AbstractImagePrototype.create(Resources.ICONS.details()));
		search.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				//MessageBox.alert("提示", "点击查询按钮", null);
				if (!combo.getValue().getValue().equals("")
						&& !lastName.getValue().equals("")) {
					Config c = new Config();
					GridConfig gc = new GridConfig();

					gc.put(combo.getValue().getValue(), lastName.getValue());
					c.put(ByGrade.GRID_FILTER, gc);
					grid.load(c);
				}
			}
		});
		final ButtonGroup group = new ButtonGroup(2);
		
		group.add(l1);
		group.add(combo);
		group.add(l2);
		group.add(lastName);
		Button b3 = new Button("清空条件");
		b3.setIconAlign(IconAlign.TOP);
		b3.setScale(ButtonScale.LARGE);
		b3.setIcon(AbstractImagePrototype.create(Resources.ICONS.clear()));
		// b4.setIcon(AbstractImagePrototype.create(Resources.ICONS.find2()));
		b3.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				grid.clearConifgs();
				combo.clear();
				lastName.clear();

			}
		});
		tb.add(add);
		tb.add(new SeparatorToolItem());
		tb.add(delete);
		tb.add(new SeparatorToolItem());
		tb.add(update);
		tb.add(new SeparatorToolItem());
		tb.add(save);
		tb.add(new SeparatorToolItem());
		tb.add(back);
		tb.add(new SeparatorToolItem());
		tb.add(condition);
		tb.add(new SeparatorToolItem());
		tb.add(securityManager);
		tb.add(new SeparatorToolItem());
		tb.add(group);
		tb.add(new SeparatorToolItem());
		tb.add(search);
		tb.add(new SeparatorToolItem());
		tb.add(b3);
		cp.setTopComponent(tb);
	}
	/**
	 * 行编辑器，一个Grid的行编辑插件，用来对表格的一行进行编辑
	 */
	private BeanRowEditor<User> rowEditor;
	/**
	 * 增加表格的一条数据，由于有些表的字段是不需要手动填写的，有默认值，
	 * 例如很多表都有用户字段，改字段的值默认都是当前的用户，不需要用户
	 * 手动填写，目前涉及到的只有两个	user 和	createDate
	 */
	public void add() {
		final Window windowAdd = new Window();
		windowAdd.setLayout(new FitLayout());
		FormPanel simple = new FormPanel();
		simple.setHeaderVisible(false);
		//simple.setFrame(true);
		simple.setHeight(400);
		FormData formData = new FormData("-20");
		//学号
		final NumberField numberField = new NumberField();
		numberField.setAllowBlank(false);
		numberField.setFieldLabel("学号");
		numberField.setPropertyEditorType(Long.class);
		final TextField<String> firstName = new TextField<String>();
		firstName.setFieldLabel("姓名");
		firstName.setAllowBlank(false);
		firstName.getFocusSupport().setPreviousId(simple.getButtonBar().getId());
		final TextField<String> password = new TextField<String>();
		password.setFieldLabel("密码");
		password.setAllowBlank(false);
		
		final SimpleComboBox<String> combo = new SimpleComboBox<String>();
		combo.setFieldLabel("用户类型");
		combo.setTriggerAction(TriggerAction.ALL);
		combo.add("老师");
		combo.add("学生");
		
		simple.add(numberField, formData);
		simple.add(firstName, formData);
		simple.add(password, formData);
		simple.add(combo, formData);
		simple.setButtonAlign(HorizontalAlignment.CENTER);
		
		Button save = new Button("保存");
		Button canel = new Button("放弃");
		save.addSelectionListener(new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				Long id = numberField.getValue().longValue();
				String name = firstName.getValue();
				String pd = password.getValue();
				User user = null;
				if(combo.getValue().getValue().equals("老师")){
					user = new Teacher();
				}else{
					user = new Student();	
				}
				user.setUserID(id);
				user.setName(name);
				user.setPassword(pd);
				BeanModelFactory beanModelFactory = BeanModelLookup.get().getFactory(User.class);
				BeanModel model = beanModelFactory.createModel(user);
				grid.getStore().insert(model, 0);
				Info.display("系统信息", "保存");
			}
		});
		canel.addSelectionListener(new SelectionListener<ButtonEvent>() {
			
			@SuppressWarnings("deprecation")
			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
				windowAdd.close();
			}
		});
		simple.addButton(save);
		simple.addButton(canel);
		windowAdd.add(simple);
		
		windowAdd.show();
	}

	/**
	 * 删除表格选中的行
	 */
	public void delete() {
		if (grid.getSelectionModel().getSelectedItems().size() == 0) {
			return;
		} else {
			MessageBox.confirm("警告", "你确定要删除所选项吗?",new Listener<MessageBoxEvent>() {

						@Override
						public void handleEvent(MessageBoxEvent be) {
							
							Button btn = be.getButtonClicked();
							if (btn.getItemId().equals("yes")) {
								for (BeanModel model : grid.getSelectionModel().getSelectedItems()) {
									
									grid.getStore().remove(model);
								}
							} 
						}
					});
		}
	}

	/**
	 * 修改表格中选中的行，由于每次只能修改一条，所以只能每次只选中一行
	 */
	public void modify() {
		int count = grid.getSelectionModel().getSelectedItems().size();
		if (count == 0) {
			return;
		} else if(count >1) {
			MessageBox.alert("提示", "对不起，你每次只能选择一条数据进行修改！！！", null);
		} else {
			BeanModel model = grid.getSelectionModel().getSelectedItem();
			Date createDate = model.get("createDate");
			if(createDate!=null) {
				Date now = new Date();
				if(!now.after(createDate)) {
					Info.display("提示", "你没有权限修改这条数据");
					return;
				}
			}
			System.out.println(grid.getCurrentRow()+"正在编辑为行");
			rowEditor.startEditing(grid.getCurrentRow(), true);
			rowEditor.setAdd(false);
		}
		
	}
	public void securityManager(){
		if (grid.getSelectionModel().getSelectedItems().size() != 1) {
			MessageBox.alert("提示", "请选择一个用户", null);
			return;
		}
		BeanModel model = grid.getSelectionModel().getSelectedItem();
		User user = model.getBean();
		new SecurityWindow(user,myService);
	}
	/**
	 * 保存
	 */
	public void save(){
		grid.getStore().commitChanges();
	}
	/**
	 * 撤销
	 */
	public void back(){
		
		grid.getStore().rejectChanges();
		
	}
	/**
	 * 内部类 提供BEANGRID的数据处理的监听类
	 * 处理当前的grid的数组交换
	 * 
	 * @author 韩忠金
	 * 
	 */
	public class StoreListener implements Listener<StoreEvent<BeanModel>> {

		@Override
		public void handleEvent(StoreEvent<BeanModel> be) {
			// 添加数据情况
			if (be.getType().equals(Store.Add)) {
				
				List<BeanModel> list = be.getModels();
				List<PO> users = cn.csust.net2.manager.shared.util.Utils.turnBeanModelToT(list);
				
				myService.save(users, new ServiceCallback<Void>() {
					
					@Override
					public void onSuccess(Void result) {
						Info.display("系统信息", "增加操作成功");
					}
					
				});
			} else if (be.getType().equals(Store.Remove)) {
					PO po = be.getModel().getBean();
					myService.delete(po,new ServiceCallback<Void>() {
	
						@Override
						public void onSuccess(Void result) {
	
							Info.display("系统信息", "删除操作成功");
	
						}
					});
				
				
			} else if (be.getType().equals(Store.Filter)) {
				
				Info.display("系统信息", "条件成功");
				
			}else if (be.getType().equals(Store.Update)) {
				
				if(be.getOperation()==RecordUpdate.COMMIT){
					PO po = be.getModel().getBean();
						myService.update(po,new ServiceCallback<Void>() {
		
							@Override
							public void onSuccess(Void result) {
		
								Info.display("系统信息", "Update操作成功");
		
							}
						});
				
				}
				
			}
		}
	}
}
